package com.generalbackend.role.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.generalbackend.role.mapper.UserRoleMapper;
import com.generalbackend.role.model.entity.UserRole;
import com.generalbackend.role.model.query.UserRoleQuery;
import com.generalbackend.role.service.IUserRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.generalbackend.common.constants.Constants.DATA;
import static com.generalbackend.common.constants.Constants.TOTAL;

/**
* @Description 用户角色关联表业务层实现类
* @author tim.xie
* @date 2021-12-16 13:24
*/

@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {
    private Logger LOG = LoggerFactory.getLogger(UserRoleServiceImpl.class);

	@Autowired
	private UserRoleMapper userRoleMapper;

	@Override
	public Boolean insert(UserRole userRole) {
        // 新增校验
        checkUserRole(userRole);
        // 填充额外属性
        fillUserRole(userRole);
        Integer num = userRoleMapper.insert(userRole);
        if(num <= 0) {
         return false;
         }
		return true;
	}

	@Override
	public Boolean update(UserRole userRole) {
        // 修改校验
        checkUserRole(userRole);
        // 填充额外属性
        fillUserRole(userRole);
        Integer num = userRoleMapper.updateById(userRole);
        if(num <= 0) {
          return false;
        }
		return true;
	}
    /**
    * 新增或者修改校验
    * @param userRole
    * @return
    */
    private void checkUserRole(UserRole userRole) {

    }
    /**
    *填充额外属性
    **/
    private void fillUserRole(UserRole userRole) {

    }

	@Override
	public Boolean deleteById(String id) {
        userRoleMapper.deleteById(id);
		return true;
	}

	@Override
	public UserRole selectById(String id) {
        UserRole userRole = userRoleMapper.selectById(id);
        return userRole;
	}
    @Override
    public JSONObject list(UserRoleQuery userRoleQuery) {
        JSONObject result = new JSONObject();
        Page<UserRole> page = new Page<>(userRoleQuery.getOffset(), userRoleQuery.getLimit());
        List<UserRole> userRoleList = userRoleMapper.list(page,userRoleQuery);
        result.put(TOTAL,  page.getTotal());
        result.put(DATA, userRoleList);
        return result;
    }

    @Override
    public Boolean deleteByUserRole(Long roleId, Long userId) {
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getRole, roleId)
                .eq(UserRole::getUser, userId);
        int num = userRoleMapper.delete(queryWrapper);
        return num > 0 ? true : false;
    }


}
